package com.moorecat.app;

import java.util.ArrayList;
import java.util.UUID;

import android.app.ActivityGroup;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.moorecat.R;
import com.moorecat.http.HttpUtils;

/**
 * @author pengfei.xu
 * @version 创建时间：2011-6-12 上午07:49:38 类说明
 */
public class BusinessGallery extends ActivityGroup {

	private static String TAG = "BusinessGallery";

	public static BusinessGallery instance;

	private ViewGroup viewGroup;

	private TextView imageTip;

	private int total = 0;

	public int current = 0;

	private long taskId;

	private int shopId;

	Handler handler = new Handler();

	Runnable monitor = new Runnable() {

		@Override
		public void run() {
			imageTip.setText(current + "/" + total);
			handler.postDelayed(monitor, 500);

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.business_gallery);
		instance = this;
		imageTip = (TextView) findViewById(R.id.image_tip);
		viewGroup = (GalleryViewGroup) findViewById(R.id.viewGroup);
		handler.post(monitor);
		shopId = getIntent().getIntExtra("shopId", 0);
		// shopId = 835;
		if (shopId > 0) {
			new LoadImageTask().execute(shopId);
		} else {
			Log.e(TAG, "没有获取到商家ID");
		}
	}

	public class LoadImageTask extends
			AsyncTask<Integer, Integer, ArrayList<String>> {

		private boolean success = false;

		@Override
		protected ArrayList<String> doInBackground(Integer... params) {
			ArrayList<String> images = null;
			try {
				images = HttpUtils.fetchShopGallery(params[0]);
				success = true;
			} catch (Exception e) {
				success = false;
				e.printStackTrace();
			}
			return images;
		}

		@Override
		protected void onPostExecute(ArrayList<String> result) {
			super.onPostExecute(result);
			if (success) {
				total = result.size();
				if (total > 0) {
					current = 1;
				} else {
					handler.removeCallbacks(monitor);
					imageTip.setText("该商家未提供图片");
				}
				for (String picPath : result) {
					Intent intent = new Intent(BusinessGallery.this,
							BusinessGalleryItem.class);
					String id = UUID.randomUUID().toString();
					intent.putExtra("picPath", picPath);
					View view = getLocalActivityManager().startActivity(id,
							intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
							.getDecorView();
					viewGroup.addView(view);
				}
				// if (total > 0) {
				// new BitmapTask().execute(result);
				// }
			}
		}

	}

}
